import { reqGetCode, reqUserLogin, reqUserRegister } from '@/api'

const state = {
    code: '',
    token: '', 
    userInfo:{}

}
const mutations = {
    RECEIVE_CODE(state, code) {
        state.code = code
    },
    RECEIVE_TOKEN(state, token) {
        state.token = token
    },
    RECEIVE_USERINFO(start,userInfo){
        start.userInfo = userInfo
    }

}
const actions = {
    //验证码
    async getCode({ commit }, phone) {
        const result = await reqGetCode(phone)
        if (result.code === 200) {
            commit('RECEIVE_CODE', result.data)
            return result.data
        } else {
            return Promise.reject(new Error('failed'))
        }
    },

    //注册
    async userRegister({ commit }, userInfo) {
        const result = await reqUserRegister(userInfo)
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },

    //登录
    async userLigin({ commit }, userInfo) {
        const result = await reqUserLogin(userInfo)
        if (result.code === 200) {
            commit('RECEIVE_TOKEN', result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },

    //获取用户信息
    async getUserInfo({ commit }){
        const result = await reqGetUserInfo()
        if(result.code === 200){
            commit('RECEIVE_USERINFO',result.data)
        }
    }
}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}